<template>
    <d2-container>
        <el-main>
            <el-dialog title="退款" :visible.sync="showReimburse" style='position:fixed;left:30vw;width: 40vw;top:10vh;'>
              <p><b>退款金额不能大于订单金额</b></p>
              退款金额：<el-input placeholder="退款金额（元）" v-model="reimburseAmount" type='number' step='0.1' >
              </el-input>
             
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmReimburse">确认退款</el-button>
                <el-button type="secondary" @click="showReimburse = false">关闭</el-button>
              </div>
             </el-dialog>

            <el-form ref="productOrderForm" :model="productOrderForm" label-width="80px" label-position="left"
                     :rules="formRules">

                <el-form-item label="转出校区">
                    <el-radio-group v-model="productOrderForm.school" :disabled="true"
                                    >
                        <el-radio v-for="value in options.schoolOption" :label="value._id" :key="value._id">
                            {{value.name}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="购买方">
                    <el-radio-group v-model="productOrderForm.buyer" :disabled="true">
                        <el-radio :label="1" v-show="headquarter == 1">校区</el-radio>
                        <el-radio :label="2">学生</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item v-if="productOrderForm.buyer == 1" label="购买校区">
                    <el-button
                            @click="searchSchool"
                            style="float:left;margin:10px"
                            icon="el-icon-plus"
                            size="small"
                            type="primary"
                            :disabled="disabled"
                    >选择购买的校区
                    </el-button>
                    <el-dialog title="校区列表" :visible.sync="status.selectSchool">
                        <el-table :data="schoolList">
                            <el-table-column property="name" label="校区名称"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="addSchool(scope.row)" type="text">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="status.selectSchool = false">确认</el-button>
                        </div>
                    </el-dialog>
                    <el-table :data="select.selectSchoolList" border style="width: 100%">
                        <el-table-column prop="name" label="校区名称"></el-table-column>
                        <el-table-column  label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteSchoolClick(scope.$index)" type="text" size="small"
                                           :disabled="disabled">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item v-if="productOrderForm.buyer == 2" label="购买学生" prop="selectedStudentList">
                     <div style="display: inline-block;float:right;font-size:15px" >
                    <el-button @click='showReimburse = true' :disabled="disabled" v-if='productOrderForm.reimbursedShow'>退款</el-button>
                  </div>
                    <el-button
                            @click="status.selectStudent = true"
                            style="float:left;margin:10px"
                            icon="el-icon-plus"
                            size="small"
                            type="primary"
                            :disabled="true">
                        选择购买的学生
                    </el-button>

                    <el-dialog title="学生列表" :visible.sync="status.selectStudent">
                        <el-input placeholder="请输入学生姓名" v-model="search.searchStudentName" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchStudent"></el-button>
                        </el-input>
                        <el-table :data="studentList">
                            <el-table-column property="name" label="学生姓名"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="addStudent(scope.row)" type="text">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="status.selectStudent = false">确认</el-button>
                        </div>
                    </el-dialog>
                    <el-table :data="select.selectStudentList" border style="width: 100%">
                        <el-table-column prop="name" label="学生姓名"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteStudentClick(scope.$index)" type="text" size="small"
                                           :disabled="true">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item label="经办员工" prop="selectedStaffList">
                    <el-button
                            @click="status.selectStaff = true"
                            style="float:left;margin:10px"
                            icon="el-icon-plus"
                            size="small"
                            type="primary"
                            :disabled="disabled">
                        选择经办的员工
                    </el-button>

                    <el-dialog title="员工" :visible.sync="status.selectStaff">
                        <el-input placeholder="请输入员工姓名" v-model="search.searchStaffName" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchStaff"></el-button>
                        </el-input>
                        <el-table :data="staffList">
                            <el-table-column property="name" label="员工姓名"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="addStaff(scope.row)" type="text">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="status.selectStaff = false">确认</el-button>
                        </div>
                    </el-dialog>

                    <el-table :data="select.selectStaffList" border style="width: 100%">
                        <el-table-column prop="name" label="经办人姓名"></el-table-column>
                        <el-table-column  label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteStaffClick(scope.$index)" type="text" size="small"
                                           :disabled="disabled">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item label="采购列表" prop="productOrder">

                    <el-button
                            @click="selectProduct"
                            style="float:left;margin:10px"
                            icon="el-icon-plus"
                            size="small"
                            type="primary"
                            :disabled="true">
                        添加采购的商品
                    </el-button>

                    <el-dialog title="商品列表" :visible.sync="status.selectProduct">

                        <el-input placeholder="请输入商品名称" v-model="search.searchProductName" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchProduct"></el-button>
                        </el-input>

                        <el-table :data="productList">
                            <el-table-column property="name" label="商品名称"></el-table-column>
                            <el-table-column prop="wholeSalePrice" label="单价"
                                             v-if="productOrderForm.buyer == 1"></el-table-column>
                            <el-table-column prop="sellingPrice" label="单价" v-else></el-table-column>
                            <el-table-column prop="storage" label="库存"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button v-if="scope.row.storage > 0" @click="addProduct(scope.row)" type="text">添加</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="status.selectProduct = false">确认</el-button>
                        </div>
                    </el-dialog>

                    <el-table :data="productOrderForm.productOrder" border style="width: 100%">

                        <el-table-column prop="product.name" label="商品名称"></el-table-column>
                        <!-- <el-table-column prop="productCategory[0].name" label="商品种类"></el-table-column> -->
                        <el-table-column prop="product.wholeSalePrice" label="单价(元)"
                                         v-if="productOrderForm.buyer == 1"></el-table-column>
                        <el-table-column prop="product.sellingPrice" label="单价(元)" v-else></el-table-column>
                        <el-table-column prop="product.storage" label="库存" disabled="disable"></el-table-column>
                        <el-table-column label="数量">
                            <template slot-scope="scope">
                                <input v-model="productOrderForm.productOrder[scope.$index].amount"
                                       style="width:50px" type="number" min="0"
                                       @change="countChange(scope.row)" :disabled="disabled"></input>
                            </template>
                        </el-table-column>
                        <el-table-column  label='小计(元)'>
                            <template slot-scope="scope">
                            {{parseFloat(productOrderForm.productOrder[scope.$index].amount * productOrderForm.productOrder[scope.$index].product.sellingPrice).toFixed(2)}}
                             </template>
                    </el-table-column>
                        <el-table-column  label="领取状态" disabled="disable">
                            <template slot-scope="scope">
                            <el-checkbox v-model="productOrderForm.productOrder[scope.$index].picked" style='font-size: 18px' :disabled="disabled"></el-checkbox>
                            </template>
                        </el-table-column>
                       <!--  <el-table-column fixed="right" label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteClick(scope.$index)" type="text" size="small"
                                           :disabled="disabled">删除
                                </el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                </el-form-item>
                <el-form-item>
            <div style="position: relative;color:#98A0A7;display: inline-block;width: 100px">对内备注</div>
                
                <el-input style="position: relative;display: inline-block;width: 40%" v-model='productOrderForm.memoIn' placeholder='内部人员可见' :disabled="disabled">
                    
                </el-input>

                <div style="position: relative;color:#98A0A7;display: inline-block;width: 100px;left:10px">对外备注</div>
                
                <el-input style="position: relative;display: inline-block;width: 40%" v-model='productOrderForm.memoOut' placeholder='订单打印可见' :disabled="disabled">
                    
                </el-input>

            </div>
        </el-form-item>


                <el-form-item label="支付方式" prop="payWay">
                    <el-radio-group v-model="productOrderForm.payWay" :disabled="disabled">
                        <el-radio :label="0">现金</el-radio>
                        <el-radio  :label="1" v-show="productOrderForm.buyer == 2">银行卡</el-radio>
                        <el-radio  :label="2">支付宝</el-radio>
                        <el-radio  :label="3">微信</el-radio>

                    </el-radio-group>
                </el-form-item>

                <el-form-item label="支付状态" prop="payStatus">
                    <el-radio-group v-model="productOrderForm.payStatus" :disabled="true">
                        <el-radio v-for="item of this.options.payStatusOption"
                                  :key="item.value"
                                  :label="item.value">
                            {{item.label}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>


               


                <el-form-item label="应收合计">
                    {{total}}
                </el-form-item>

                <el-form-item label="优惠" prop="discount">
                    <el-input v-model.number="productOrderForm.discount" type="number" min="0"
                              :disabled="disabled"></el-input>
                </el-form-item>

                <el-form-item label="实收合计">
                    {{real}}
                </el-form-item>

            </el-form>


            <el-row :span="6" style="margin-top:10px;height:40px"><span style='width:2px;height:100%;background-color:rgb(52, 178, 211) ;color: rgb(52, 178, 211);margin-right: 3px'>_</span>
          提成信息
          <el-button @click="showStaff = true" type='primary' style='height:30px;position: relative;top:0px;font-size: 14px;padding: 5px;margin-left:50px;display: inline-block;' :disabled='disabled'>添加提成人员
          </el-button>
      </el-row>

          
           <el-row v-if="productOrderForm.bonus.length == 0" style='background-color: white;height:150px;margin-top: 10px;border-width: 1px;border-color: #D4DFE5;border-style: solid;'>
            <div style="color:#CACBCC;width: 100%;text-align: center;line-height: 150px;height: 150px">
              <el-button type='primary' @click='showStaff = true' :disabled="disabled">添加提成人员</el-button>
            </div>
        </el-row>

            <el-row style='background-color:white;width: 100%;position: relative;border-width: 1px;border-color: #D4DFE5;border-style: solid;margin-bottom:20px;margin-top: 10px;border-width: 1px;border-color: #D4DFE5;border-style: solid;'  v-else>
            
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5">
            </div>

            <div style="width: 100%;position: relative;">
                <div v-for='(commission,index) in productOrderForm.bonus' style="margin-bottom:10px;height:60px;position: relative;">
                    <div style="position: relative;left:30px;display: inline-block;width: 100px;height: 60px">{{commission.staff.name}}</div>
                    <!-- <div style="position: relative;left:80px;color:#98A0A7;display: inline-block;width: 100px;height: 60px;line-height: 60px">提成类型：</div>
                    <el-select v-model="commission.type"  style='display: inline-block;left:255px;position:absolute;top:15px;width: 150px' :disabled='disabled'>
                    <el-option
                      v-for="item in types"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select> -->
                  <div style="display: inline-block;">
                    <div style="width: 70px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:250px;color:#98A0A7;">百分比:</div>
                    <el-input style="position: relative;width: 100px;left:250px;display: inline-block;" v-model='commission.percentage' :disabled='disabled' @change='commissionChange(index)' type='number'> </el-input>
                  </div>
                  <div style="display: inline-block;">
                    <div style="width: 60px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:300px;color:#98A0A7;">提成:</div>
                        <el-input style="position: relative;width: 100px;display: inline-block;left:300px " v-model='commission.commission' :disabled='true'> </el-input>
                  </div>
                  <div style="display: inline-block;">
                    <div style="width: 60px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:400px;color:#98A0A7;">备注:</div>
                        <el-input style="position: relative;width: 200px;display: inline-block;left:400px " v-model='commission.memo' :disabled="!edit"> </el-input>
                  </div>
                    <button style="height:30px;width: 30px;background-color: #F6E4E7;border-style: solid;border-width: 1px;border-color: #FB6363;border-radius: 3px;position: absolute;top:20px;right:50px" @click="removeCommission(index)"><i class="el-icon-close" style="color: #FB6363;" disabled='disabled'></i> 
                    </button>
                  <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:-9px"></div>
                </div>
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:40px">
            </div>

        </el-row>


        </el-main>
        <el-footer style="text-align: center">
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button type="primary" @click="resetForm('productOrderForm')">重置</el-button>
            <el-button @click="edit" v-show="editShow">修改</el-button>
        </el-footer>

        <el-dialog title="员工" :visible.sync="showStaff" >
                        <el-input placeholder="请输入员工姓名" v-model="search.staffName" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchStaff"></el-button>
                        </el-input>
                        <el-table :data="staffList" height="500">
                            <el-table-column property="name" label="员工姓名"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="addBonusStaff(scope.$index)" type="text">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="showStaff = false">确认</el-button>
                        </div>
                    </el-dialog>
                    </el-dialog>
    </d2-container>


</template>
<script>
    import request from "@/plugin/axios";
    import {mapState} from "vuex";

    export default {
        data() {
            return {
                formRules: {
                    name: [
                        {required: true, message: '请输入学生姓名', trigger: 'blur'},
                        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                    ],
                    studentId: [
                        {required: true, message: '请输入学号', trigger: 'change'}
                    ],
                    gender: [
                        {required: true, message: '请选择学生性别', trigger: 'change'}
                    ],
                    age: [
                        {required: true, message: '请输入家长年龄', trigger: 'change'},
                        {type: 'number', min: 5, max: 100, message: '年龄范围在5-100之间', trigger: 'change'}

                    ],
                    school: [
                        {required: true, message: '请选择所在校区', trigger: 'change'}
                    ],
                    buyer: [
                        {required: true, message: '请选择购买者类型', trigger: 'change'}
                    ],
                    staff: [
                        {required: true, message: '请选择购买者类型', trigger: 'change'}
                    ],
                    payType: [
                        {required: true, message: '请选择付费类型', trigger: 'change'}
                    ],
                    cellphone: [
                        {required: true, message: '手机号不能为空', trigger: 'change'},
                        {type: 'number', message: '请输入11位合法手机号', trigger: 'change'}
                    ],
                    birthday: [
                        {type: 'date', required: true, message: '请选择出生日期', trigger: 'blur'}
                    ],
                    selectedSchoolList: [
                        {type: 'array', required: true, message: '请选择购买校区', trigger: 'blur'}
                    ],
                    selectedStudentList: [
                        {type: 'array', required: true, message: '请选择购买学生', trigger: 'blur'}
                    ],
                    productOrder: [
                        {type: 'array', required: true, message: '请选择采购商品', trigger: 'blur'}
                    ],
                    payWay: [
                        {required: true, message: '请选择支付方式', trigger: 'change'}
                    ],
                    payStatus: [
                        {required: true, message: '请选择支付状态', trigger: 'change'}
                    ],

                    discount: [
                        {required: true, min: 0, type: 'number', message: '请输入合法优惠金额', trigger: 'change'}
                    ],
                },

                productOrderForm: {

                    //购买者类型
                    buyer: undefined,
                    //出售的校区
                    bonus : [],
                    school: undefined,
                    selectedSchool: undefined,
                    selectedStudent: undefined,
                    selectedStaff: undefined,
                    productOrder: [],
                    payWay: undefined,
                    payStatus: undefined,
                    discount: 0,
                    reimbursedShow : false
                },
                showReimburse : false,
                showStaff :false,
                options: {
                    payStatusOption: [
                        {
                            label: '待支付',
                            value: 0
                        },
                        {
                            label: '已支付',
                            value: 1
                        }
                    ],
                    schoolOption: []
                },
                status: {
                    selectStudent: false,
                    selectSchool: false,
                    selectStaff: false,
                    selectProduct: false,
                },
                schoolList: [],
                studentList: [],
                staffList: [],
                productList: [],
                search: {
                    searchStudentName: undefined,
                    searchStaffName: undefined,
                    searchProductName: undefined
                },
                select: {
                    selectStudentList: [],
                    selectStaffList: [],
                    selectSchoolList: []
                },
                editShow: false,
                disabled: false,
                id: undefined,
                searchName: undefined,
                searchCount: undefined,
                searchSchoolName: undefined,
                searchSchoolCount: undefined,
                searchStudentCount: undefined,
                searchStaffCount: undefined,
                student: undefined,
                productStaff: undefined,
                total:0,
                headquarter : undefined,
                reimburseAmount : undefined

            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
            // total: function () {
            //     let t = 0;
            //     this.productOrderForm.productOrder.forEach((value, index) => {
            //         t = t + parseInt(value.count) * value.sellingPrice
            //     });
            //     this.productOrderForm.total = t;
            //     return t;
            // },
            real: function () {
                let t = 0
                t = this.total - this.productOrderForm.discount;
                return t;
            }
        },
        methods: {
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            /**
             * school选择相关
             */
            getSchoolList(page, pageSize) {
                let data = {};
                (data.page = page), (data.pageSize = pageSize);
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                    data
                }).then(res => {
                    this.schoolList = []
                    res.data.school.forEach((value, index) => {

                        if (value._id != this.productOrderForm.school) {
                            this.schoolList[this.schoolList.length] = {_id: value._id, name: value.name}
                        }
                    })


                });
            },
            addSchool(e) {
                this.select.selectSchoolList = [];
                this.select.selectSchoolList.push(e);
                this.productOrderForm.selectedSchool = e._id;
                this.$message({
                    showClose: true,
                    message: '添加成功',
                    type: 'success'
                });
            },
            schoolCurrentChange(e) {
                this.getSchoolList(e);
            },
            deleteSchoolClick(e) {
                this.select.selectSchoolList.splice(e,1)
                this.productOrderForm.selectedSchool = undefined
            },
            searchSchool() {
                this.status.selectSchool = true;
                this.getSchoolList(1);
            },

            /**
             *
             * student相关
             *
             */
            searchStudent() {
                this.getStudentList(1);
            },
            getStudentList(page) {
                request({
                    url: "/student/getStudentList",
                    method: "post",
                    data: {
                        page: page,
                        pageSize: 100,
                        name: this.search.searchStudentName,
                        school: this.options.schoolOption.map(value => value._id)
                    }
                }).then(res => {
                    this.studentList = res.data.students;
                    this.searchStudentCount = res.data.count;

                });
            },
            
            addStudent(e) {
                this.select.selectStudentList = [];
                this.select.selectStudentList.push(e);
                this.productOrderForm.selectedStudent = e._id;
                this.$message({
                    showClose: true,
                    message: '添加成功',
                    type: 'success'
                });
            },
            deleteStudentClick(e) {
                this.productOrderForm.selectedStudentList = undefined
                this.select.selectStudentList.splice(e,1);
            },


            /**
             *
             * staff相关
             *
             */

            searchStaff() {
                this.getStaffList(1);
            },
            getStaffList(page) {
                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: {
                        page: page,
                        pageSize: 10000,
                        name: this.searchStaffName,
                        school: this.school._id
                    }
                }).then(res => {
                    this.staffList = res.data.staff;
                    this.searchStaffCount = res.data.count;
                });
            },
            addStaff(e) {
                this.select.selectStaffList = [];
                this.select.selectStaffList.push(e);
                this.productOrderForm.selectedStaff = e._id;
                request({
                    url: "/staff/getStaffOne",
                    method: "post",
                    data: {
                        id: e._id
                    }
                }).then(res => {
                    if (res.code == 200) {
                        this.productOrderForm.percentage = parseInt(res.data.productProportion);
                        this.$message({
                            showClose: true,
                            message: '添加成功',
                            type: 'success'
                        });
                    }
                });
            },
            addBonusStaff(index){
                this.productOrderForm.bonus.push(
                  {
                    staff : this.staffList[index],
                    percentage : 0,
                    commission : 0,
                    memo : ''
                  }
                )
            },
            deleteStaffClick(e) {
                this.productOrderForm.selectedStaff = undefined
                this.select.selectStaffList.splice(e,1)
            },

              commissionChange(index){
                console.log(this.productOrderForm.total,this.productOrderForm.discount)
                this.productOrderForm.bonus[index].commission = Math.round((this.productOrderForm.total - this.productOrderForm.discount) *  this.productOrderForm.bonus[index].percentage) / 100

                if (this.productOrderForm.bonus[index]._id != undefined){
                  this.productOrderForm.bonus[index].modified = true
                }

  },

  removeCommission(index){
    if (this.productOrderForm.bonus[index]._id != undefined){
      //confirm delte this commission
      this.$confirm('如果已经发放提成，请联系相关人员进行下一步操作','需要删除该提成吗？',{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then((value) => {
                request({
                    url: "/staffCommission/removeStaffCommission",
                    method: "post",
                    data: {id:this.productOrderForm.bonus[index]._id,orderid:this.productOrderForm._id}
                }).then(res => {
                    if (res.code == 200){
                      this.$alert('','删除成功',{
                                confirmButtonText :'确定',
                                type: 'info'
                            }).then((value) =>{
                              this.productOrderForm.bonus.splice(index,1)
                            })
                    }
                });
        })
        .catch(()=>{
          // this.getCourseOrderOne(this.id)
        })
    }
    else{
      this.productOrderForm.bonus.splice(index,1)
    }
  },


            /**
             *
             * product相关
             *
             */

            searchProduct() {
                this.getProductList(1);
            },
            getProductList(page) {
                request({
                    url: "/product/getProductList",
                    method: "post",
                    data: {
                        page: page,
                        pageSize: 99999999,
                        name: this.search.searchProductName,
                        school: [this.productOrderForm.school]
                    }
                }).then(res => {
                    if (res.code == 200) {
                        this.productList = res.data.product
                        this.searchCount = res.data.count
                    }
                });
            },
            addProduct(e) {
                if (this.productOrderForm.productOrder.map(event => {
                    return event._id
                }).indexOf(e._id) == -1) {
                    e.amount = 0
                    this.productOrderForm.productOrder.push(e)
                } else {
                    this.$message({
                        showClose: true,
                        message: '已经添加这个商品了哦',
                        type: 'error'
                    });
                }
            },
            deleteClick(e) {
                this.productOrderForm.productOrder.splice(e, 1)
            },

            /**
             *
             *
             *
             */


            getProductOrderOne(id) {
                request({
                    url: "/productOrder/getProductOrderOne",
                    method: "post",
                    data: {id: id}
                }).then(res => {
                    this.id = res.data._id;
                    this.productOrderForm._id = res.data._id
                    this.productOrderForm.buyer = res.data.buyer;
                    this.productOrderForm.school = res.data.school;
                    this.productOrderForm.payWay = res.data.payWay;
                    this.total = res.data.total;
                    this.productOrderForm.discount = res.data.discount;
                    this.productOrderForm.payStatus = res.data.payStatus;
                    this.productOrderForm.discount = res.data.discount;
                    // this.productOrderForm.percentage = res.data.percentage;
                    this.productOrderForm.bonus = res.data.bonus
                    this.productOrderForm.total = res.data.total
                    this.productOrderForm.memoIn = res.data.memoIn
                    this.productOrderForm.memoOut = res.data.memoOut

                    // res.data.productOrder.forEach(element => {
                    //     element.product.amount = element.amount
                    // });
                    this.productOrderForm.productOrder = res.data.productOrder

                    for (var i = 0 ; i <this.productOrderForm.productOrder.length;i++ ){
                        this.productOrderForm.productOrder[i].picked = this.productOrderForm.productOrder[i].picked == 1 ? true : false
                        this.productOrderForm.productOrder[i].origin = this.productOrderForm.productOrder[i].amount
                        this.productOrderForm.productOrder[i].originPicked = this.productOrderForm.productOrder[i].picked == 1 ? true : false
                    }

                    if (res.data.reimbursed != undefined){
                        this.productOrderForm.reimbursedShow = false
                    }
                    else if (res.data.payStatus == 1){
                        this.productOrderForm.reimbursedShow = true
                    }
                    this.productOrderForm.staff = res.data.agent;
                    this.productOrderForm.school = res.data.school;
                    this.productOrderForm.student = res.data.student;
                    this.select.selectSchoolList.push(res.data.school);
                    this.select.selectStaffList.push(res.data.agent);
                    this.select.selectStudentList.push(res.data.student);
                })
            },


            submit() {
                let data = {};
                let url = "/productOrder/addProductOrder";
                if (this.id != undefined) {
                    data.productOrder = this.id;
                    url = "/productOrder/updateProductOrder";
                }
                if (this.productOrderForm.total <=0){
                          this.$confirm('是否继续？','当前订单金额小于等于0',{
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning"
                    }).then((value) => {
                        console.log('asdds')
                           // return false
                    })
                    .catch(()=>{
                        console.log('dddd')
                      // this.getCourseOrderOne(this.id)
                      return false
                    })
                }
                if (this.productOrderForm.buyer == 1) {
                    if (!this.productOrderForm.selectedSchool) {
                        this.$message({
                            showClose: true,
                            message: '未选择校区',
                            type: 'error'
                        });
                        return false
                    } 

                } else if (this.productOrderForm.buyer == 2) {
                    if (!this.productOrderForm.student) {
                        this.$message({
                            showClose: true,
                            message: '未选择学生',
                            type: 'error'
                        });
                        return false
                    } 
                }

                let modified = false
                let originpick = false
                let i = 0 

                while (i < this.productOrderForm.bonus.length){
                    if (this.productOrderForm.bonus[i].percentage <= 0){
                      this.$alert('','提成不能为0',{
                                  confirmButtonText: "确定"
                                })
                      return false
                      }
                       
                      else{
                        i += 1
                      }
                    }
                i = 0 
                while (i < this.productOrderForm.productOrder.length){
                    if (this.productOrderForm.productOrder[i].originPicked != this.productOrderForm.productOrder[i].picked){
                        originpick = true
                        console.log('hahaha',this.productOrderForm.productOrder[i].originPicked,this.productOrderForm.productOrder[i].picked,this.productOrderForm.productOrder[i].originpicked == this.productOrderForm.productOrder[i].picked)
                        i = this.productOrderForm.productOrder.length
                    }
                    else{
                        i += 1
                    }
                }
                i = 0 
                 while (i < this.productOrderForm.productOrder.length){
                    if (this.productOrderForm.productOrder[i].amount != this.productOrderForm.productOrder[i].origin){
                        originpick = true
                        i = this.productOrderForm.productOrder.length
                    }
                    else{
                        i += 1
                    }
                }
                i = 0
                while (i < this.productOrderForm.bonus.length){
                    if (this.productOrderForm.bonus[i].modified){
                        modified = true
                        i = this.productOrderForm.bonus.length
                    }
                    else{
                        i += 1
                    }
                }               
                
                if ((modified) || (originpick)){
                    this.$confirm( modified ? '如果已经发放提成，请联系相关人员进行下一步操作' : '','该订单修改可能改变' + (originpick ? '(教材库存)' : "") + (modified ? '(提成数据)。': ""),{
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning"
                        }).then((value) => {
                            request({
                                url: url,
                                method: "post",
                                data : {data:this.productOrderForm}
                            }).then(res => {
                                if (res.code == 200) {
                                    this.$alert("", "提交成功", {
                                        confirmButtonText: "确定"
                                    }).then((value) => {
                                        this.refresh = true
                                        this.$router.back(-1)
                                        
                                    });
                                }
                                // 返回数据
                            });

                        })
                }
                else{
                    request({
                        url: url,
                        method: "post",
                        data : {data:this.productOrderForm}
                        }).then(res => {
                            if (res.code == 200) {

                                this.$alert("", "提交成功", {
                                    confirmButtonText: "确定"
                                }).then((value) => {
                                    this.$router.back(-1)
                                });
                            }
                            // 返回数据
                        });
                        }

                
            },

            edit() {
                this.disabled = false;
            },

            currentChange(e) {
                this.getProductList(e);
            },

            studentCurrentChange(e) {
                this.getStudentList(e);
            },

            staffCurrentChange(e) {
                this.getStaffList(e);
            },

            countChange(row) {
                if (row.amount<= 0 || row.amount > row.product.storage) {

                    // this.productOrderForm.productOrder[index].count = 1

                    this.$message({
                        showClose: true,
                        message: '数量不合法，请重新输入',
                        type: 'error'
                    });


                } else{
                    let total = 0
                    for (let i = 0; i < this.productOrderForm.productOrder.length; i++) {
                        if (this.productOrderForm.buyer == 1) {
                            total += this.productOrderForm.productOrder[i].wholeSalePrice * this.productOrderForm.productOrder[i].amount
                        } else if (this.productOrderForm.buyer == 2) {
                            total += this.productOrderForm.productOrder[i].product.sellingPrice * this.productOrderForm.productOrder[i].amount
                        }
                    }
                    this.productOrderForm.total = total
                    this.total = total
                    console.log(total,'aha total')
                }

            },
            selectProduct(){
                if(this.productOrderForm.buyer ==1 || this.productOrderForm.buyer ==2){
                    this.status.selectProduct = true
                }else{
                    this.$alert('', '请选择购买方', {
                    confirmButtonText: '确定'
                    });
                }
            },

            confirmReimburse (){
              if (this.reimburseAmount > this.productOrderForm.total){
                this.$alert('退款金额不能大于总金额')
                return
              }
              this.$confirm('退款金额为' + this.reimburseAmount + '元。退款后，库存如需调整请去进销存调整。','确认要退款吗？',{}).then(()=>{
              request({
                    url: "/productOrder/reimburseProductOne",
                    method: "post",
                    data: {
                       id : this.id,
                       amount : this.reimburseAmount
                    }
                }).then(res => {
                    if (res.code == 200){
                      this.$message('退款成功！')
                      this.showReimburse = false
                      this.getProductOrderOne(this.id)
                    }

                });
            }).catch(()=>{

            })

            },


        },
    beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        next()
      },

        created() {
            this.school = this.info.school[0]
            if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
                this.headquarter = 1
            }
    else{
        this.productOrderForm.buyer = 2
    }
            this.options.schoolOption = this.info.school;
            this.productOrderForm.fromSchool = this.options.schoolOption[0]._id;

            //零时修正
            if (this.info.role.indexOf('root') > -1) {
                this.productOrderForm.fromSchool = this.options.schoolOption[1]._id;
            }


            if (this.$route.query.id != undefined) {
                this.editShow = true;
                this.disabled = true;
                this.id = this.$route.query.id
                this.getProductOrderOne(this.$route.query.id)

            }
        }
    }
</script>
